package small.common.http.util;

import small.common.http.constants.HttpConstants;
import small.common.core.util.StringUtil;

/**
 * 构建上下文路径工具类
 * @Author zhoujin
 * @Date 2022/11/22 16:49
 */
public class ContextPathUtil {

    private static final String ROOT_WEB_CONTEXT_PATH = "/";

    /**
     * 规范url
     * @param curServer 服务地址
     * @return
     */
    public static String normalizeContextUrl(String curServer){
        if (curServer.startsWith(HttpConstants.HTTPS) || curServer.startsWith(HttpConstants.HTTP)) {
            return curServer;
        } else {
            curServer = getDefaultPrefix() + curServer;
        }
        return curServer;
    }

    /**
     * 规范url
     * @param curServer 服务地址
     * @return
     */
    public static String normalizeContextUrl(String curServer,Integer port){
        curServer = normalizeContextUrl(curServer) + HttpConstants.IP_PORT_SPLITER + port;
        return curServer;
    }


    /**
     * 规范url
     * @param curServer 服务地址
     * @param contextPath 上下文路径
     * @return
     */
    public static String normalizeContextUrl(String curServer,String... contextPath){
        if(StringUtil.isBlank(curServer) || contextPath == null){
            return curServer;
        }
        curServer = normalizeContextUrl(curServer);
        StringBuilder curServerBuilder = new StringBuilder(curServer);
        for (String context : contextPath) {
            curServerBuilder.append(normalizeContextPath(context));
        }
        return curServerBuilder.toString();
    }

    /**
     * 添加端口号
     * @param curServer 服务地址
     * @param serverPort 服务端口
     * @return
     */
    public static String appendPort(String curServer,int serverPort){
        return curServer = curServer + HttpConstants.IP_PORT_SPLITER + serverPort;
    }


    /**
     * 获取默认url前缀
     * @return
     */
    public static String getDefaultPrefix() {
        return HttpConstants.HTTP;
    }


    /**
     * 规范化上下文路径
     *
     * @param contextPath 原始上下文路径
     * @return normalized 上下文路径
     */
    public static String normalizeContextPath(String contextPath) {
        if (StringUtil.isBlank(contextPath) || ROOT_WEB_CONTEXT_PATH.equals(contextPath)) {
            return StringUtil.EMPTY;
        }
        return contextPath.startsWith("/") ? contextPath : "/" + contextPath;
    }
}
